package cn.pzhuweb.controller;

/**
 * @author Yancy xiao
 * @create 2022-12-14 20:24
 */

import cn.pzhuweb.pojo.Car;
import cn.pzhuweb.service.CarService;
import cn.pzhuweb.service.imp.CarServiceImp;
import cn.pzhuweb.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * Servlet implementation class TodoServlet
 */
@WebServlet("/search")
public class QueryKeyCarServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryKeyCarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    /**
     * 关键字模糊查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String key = request.getParameter("key");
        request.getSession().setAttribute("key", key);
        CarService cs = new CarServiceImp();
        List<Car> list = cs.searchByKeywords(key);
        String snum = request.getParameter("num");
        String spage = request.getParameter("page");
        int num = 10;
        try {
            num = Integer.parseInt(snum);
        } catch (NumberFormatException e) {
            num = 10;
        }
        int page = 1;
        try {
            page = Integer.parseInt(spage);
        } catch (NumberFormatException e) {
            page = 1;
        }
        List<Car> pagelist = PageUtil.splitLsit(list, page, num);
        request.getSession().setAttribute("list", pagelist);
        //导航栏
        String path = request.getContextPath() + "/search";
        StringBuffer bar = PageUtil.getBar(list, page, num, path, key);
        request.getSession().setAttribute("bar", bar);
        request.getSession().setAttribute("num", num);
        response.sendRedirect("show.jsp");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

